<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.company.ems.model.Employee" %>
<%@ page import="com.company.ems.model.User" %>
<%@ page import="java.util.List" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%
    User loginUser = (User) session.getAttribute("loginUser");
    if (loginUser == null) {
        response.sendRedirect(request.getContextPath() + "/login.jsp");
        return;
    }
    Employee employee = (Employee) request.getAttribute("employee");
    List<String> departments = (List<String>) request.getAttribute("departments");
    List<String> positions = (List<String>) request.getAttribute("positions");
    if (employee == null) {
        request.setAttribute("errorMsg", "员工不存在");
        response.sendRedirect(request.getContextPath() + "/EmployeeServlet?action=list");
        return;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
%>
<html>
<head>
    <title>编辑员工 - 员工信息管理系统</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
    <script>
        function loadPositions() {
            const dept = document.getElementById("department").value;
            const posSelect = document.getElementById("position");
            posSelect.innerHTML = "<option value=''>请选择职位</option>";
            if (!dept) return;

            const posMap = {
                "技术部": ["软件工程师", "测试工程师"],
                "市场部": ["市场专员", "营销经理"],
                "人事部": ["HR经理", "招聘专员"]
            };
            (posMap[dept] || []).forEach(pos => {
                const opt = document.createElement("option");
                opt.value = pos;
                opt.text = pos;
                // 保留当前职位选中状态
                if (pos === "<%= employee.getPosition() %>") {
                    opt.selected = true;
                }
                posSelect.appendChild(opt);
            });
        }

        function validate() {
            const name = document.getElementById("name").value.trim();
            const dept = document.getElementById("department").value;
            const pos = document.getElementById("position").value;
            const salary = document.getElementById("salary").value.trim();
            const hireDate = document.getElementById("hireDate").value;

            if (!name) {
                alert("姓名不能为空！");
                return false;
            }
            if (!dept) {
                alert("请选择部门！");
                return false;
            }
            if (!pos) {
                alert("请选择职位！");
                return false;
            }
            if (!salary || isNaN(Number(salary)) || Number(salary) <= 0) {
                alert("薪资必须为正数！");
                return false;
            }
            if (!hireDate) {
                alert("请选择入职日期！");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
<!-- 顶部导航 -->
<nav class="top-nav">
    <div class="nav-left">
        <h2>员工信息管理系统</h2>
    </div>
    <div class="nav-right">
        <span>欢迎您，<%= loginUser.getUsername() %>！</span>
        <a href="${pageContext.request.contextPath}/LogoutServlet" class="logout-btn">退出登录</a>
    </div>
</nav>

<!-- 主体内容 -->
<div class="employee-container">
    <div class="form-container">
        <div class="form-title">
            <h1>编辑员工信息（ID：<%= employee.getId() %>）</h1>
        </div>

        <%-- 错误信息 --%>
        <% if (request.getAttribute("errorMsg") != null) { %>
        <div class="error-msg"><%= request.getAttribute("errorMsg") %></div>
        <% } %>

        <%-- 编辑表单 --%>
        <form action="${pageContext.request.contextPath}/EmployeeServlet?action=edit" method="post" onsubmit="return validate()">
            <!-- 隐藏员工ID -->
            <input type="hidden" name="id" value="<%= employee.getId() %>">

            <div class="form-grid">
                <div class="form-group">
                    <label for="name">姓名 <span style="color: red;">*</span></label>
                    <input type="text" id="name" name="name" value="<%= employee.getName() %>" placeholder="请输入姓名" maxlength="100">
                </div>
                <div class="form-group">
                    <label for="department">部门 <span style="color: red;">*</span></label>
                    <select id="department" name="department" onchange="loadPositions()">
                        <option value="">请选择部门</option>
                        <% if (departments != null && !departments.isEmpty()) { %>
                        <% for (String dept : departments) { %>
                        <option value="<%= dept %>" <%= dept.equals(employee.getDepartment()) ? "selected" : "" %>>
                            <%= dept %>
                        </option>
                        <% } %>
                        <% } %>
                    </select>
                </div>
                <div class="form-group">
                    <label for="position">职位 <span style="color: red;">*</span></label>
                    <select id="position" name="position">
                        <option value="">请选择职位</option>
                        <% if (positions != null && !positions.isEmpty()) { %>
                        <% for (String pos : positions) { %>
                        <option value="<%= pos %>" <%= pos.equals(employee.getPosition()) ? "selected" : "" %>>
                            <%= pos %>
                        </option>
                        <% } %>
                        <% } %>
                    </select>
                </div>
                <div class="form-group">
                    <label for="salary">薪资（元） <span style="color: red;">*</span></label>
                    <input type="text" id="salary" name="salary" value="<%= employee.getSalary() %>" placeholder="例如：15000.00">
                </div>
                <div class="form-group">
                    <label for="email">电子邮箱</label>
                    <input type="email" id="email" name="email" value="<%= employee.getEmail() != null ? employee.getEmail() : "" %>" placeholder="请输入邮箱" maxlength="100">
                </div>
                <div class="form-group">
                    <label for="phone">联系电话</label>
                    <input type="text" id="phone" name="phone" value="<%= employee.getPhone() != null ? employee.getPhone() : "" %>" placeholder="请输入电话" maxlength="20">
                </div>
                <div class="form-group">
                    <label for="hireDate">入职日期 <span style="color: red;">*</span></label>
                    <input type="date" id="hireDate" name="hireDate" value="<%= sdf.format(employee.getHireDate()) %>">
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="submit-btn">更新</button>
                <a href="${pageContext.request.contextPath}/EmployeeServlet?action=list" class="back-btn">返回列表</a>
            </div>
        </form>
    </div>
</div>

<!-- 页脚 -->
<footer class="app-footer">
    <p>© 2025 员工信息管理系统 | 技术栈：Servlet + JSP + MyBatis（纯Java配置）</p>
</footer>
</body>
</html>